<template>
  <a-tree
    ref="aTreeSlot"
    v-model="treeData"
    :defaultExpandAll="true"
    :expandOnClickNode="false"
    @append="append"
    @remove="remove"
    customNode
  >
    <!-- 自定义文本 -->
    <template #customLabelNode="{ data, node }">
      {{ node.label }}
    </template>
    <!-- 自定义menu -->
    <template #treeMenu="{ node, data }">
      <div>
        <el-button type="primary" link @click="aTreeSlot.append(data)"
          >新增</el-button
        >
        <el-button type="danger" link @click="aTreeSlot.remove(node, data)"
          >删除</el-button
        >
      </div>
    </template>
  </a-tree>
</template>

<script setup lang="ts">
import aTree from "@/components/aTree/index.vue";

const treeData = ref([
  {
    id: 1,
    label: "Level one 1",
    children: [
      {
        id: 4,
        label: "Level two 1-1",
        children: [
          {
            id: 9,
            label: "Level three 1-1-1",
          },
          {
            id: 10,
            label: "Level three 1-1-2",
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: "Level one 2",
    children: [
      {
        id: 5,
        label: "Level two 2-1",
      },
      {
        id: 6,
        label: "Level two 2-2",
      },
    ],
  },
  {
    id: 3,
    label: "Level one 3",
    children: [
      {
        id: 7,
        label: "Level two 3-1",
      },
      {
        id: 8,
        label: "Level two 3-2",
      },
    ],
  },
]);

const aTreeSlot = ref();

let id = 1000;

function append(data) {
  const newChild = { id: id++, label: "testtest", children: [] };
  if (!data.children) {
    data.children = [];
  }
  data.children.push(newChild);
  treeData.value = [...treeData.value];
}

function remove(node, data) {
  const parent = node.parent;
  const children = parent.data.children || parent.data;
  const index = children.findIndex((d) => d.id === data.id);
  children.splice(index, 1);
  treeData.value = [...treeData.value];
}
</script>

<style>
</style>